package com.dhecp.project.business.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.framework.web.service.BaseInfoSimpleService;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.domain.ProductActiveComponent;
import com.dhecp.project.business.domain.ProductBasis;
import com.dhecp.project.business.domain.ProductCarefullyChosen;
import com.dhecp.project.business.service.ProductCarefullyChosenService;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 精品库 控制层
 * @author: hlf
 * @create: 2023-03-13 10:40
 */
@Controller
@RequestMapping("/business/productcarefullychosen")
public class ProductCarefullyChosenController extends BaseModuleController {

    private String prefix = "business/productcarefullychosen";
    private String moduleTable = ModuleTable.PRODUCT_CAREFULLY_CHOSEN;
    private String moduleTableZJ = ModuleTable.PRODUCT_ACTIVE_COMPONENT;

    @Autowired
    private ProductCarefullyChosenService chosenService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;
    @Autowired
    private BaseInfoSimpleService baseInfoSimpleService;


    /**
     * @Description: 打开查询列表页
     * @Param: [params]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-05-09 11:39
     */
    @RequiresPermissions("business:productcarefullychosen:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new ProductCarefullyChosen()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/productcarefullychosen"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");
        
    	Object importFields = dictionaryForFieldService.queryFieldFrontImport(params); //精品批量导入字段

        ModelAndView mv = this.openListPage(params);
        mv.addObject("business", "productcarefullychosen");
        mv.addObject("importFields",importFields);				//精品批量导入字段模板
        return mv;
    }

    /**
     * @Description: 打开制单页
     * @Param: [params] nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-05-09 11:39
     */
//    @RequiresPermissions("business:productcarefullychosen:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new ProductCarefullyChosen()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        ProductCarefullyChosen chosen = new ProductCarefullyChosen();
        Map<String, Object> extraButton = new HashMap<String, Object>();//额外的按钮属性
        Subject userSubject = ShiroUtils.getSubject();
        Integer enableEdit = 0;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())){
            if (userSubject.isPermitted("business:productcarefullychosen:edit")){ //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }
        extraButton = this.checkExtraButton(params);
        mv = this.gotoModelAndViewErrorPage(params, "code", "商品编码");
        if (mv.isEmpty()){
            try{
                dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
                if (dictionaryForFieldMap.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }
            	/*else{
                	productActive = productActiveService.queryProductActiveByGuid(params.get("guid").toString());
                	if (productActive == null){
                		ajaxResult = AjaxResult.error("没有查到商品信息。");
                	}else{
                    	ajaxResult = AjaxResult.success("数据获取成功。");
                	}
                }
                */
                params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
                dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
                if (dicFieldsList.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                    chosen = chosenService.findByCode(params.get("code").toString());
                    if (chosen == null){
                        ajaxResult = AjaxResult.error("没有查到商品信息。");
                    }else{
                        ajaxResult = AjaxResult.success("数据获取成功。");
                        for (SysDictionaryForPageField dicFields : dicFieldsList){
                            if (enableEdit == 0){dicFields.setFieldFrontEdit(false);}
                            Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                            Map<String, Object> productActiveMap = TypeUtils.entityToMap(chosen);
                            fieldsListMap.put("fieldContent", productActiveMap.get(fieldsListMap.get("fields")));


                            //如果有下拉控件，则根据配置获取对应下拉待选内容
                            List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                            String fieldFrontType = dicFields.getFieldFrontType();
                            String fieldSearchType = dicFields.getFieldSearchType();
                            String fieldFrontSave = dicFields.getFieldFrontSave();
                            String fieldFrontShow = dicFields.getFieldFrontShow();
                            if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")){
                                if (fieldSearchType != null && !"".equals(fieldSearchType)){
                                    if (fieldFrontSave == null || "".equals(fieldFrontSave)){
                                        fieldFrontSave = "vid";
                                    }
                                    if (fieldFrontShow == null || "".equals(fieldFrontShow)){
                                        fieldFrontShow = "vname";
                                    }
                                    dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType,fieldFrontSave,fieldFrontShow);
                                }
                            }
                            fieldsListMap.put("dropdownList", dropdownList);

                            if (fieldsListMap.get("fieldFrontType") == null){
                                fieldsListMap.put("fieldFrontType", "t_text");
                            }

                            if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                                fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                            }else {	//隐藏的字段
                                fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                            }
                        }
                    }
                }
            }
            catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            //取商品子件列表网格
            params.put("moduleTable", moduleTableZJ);
            params.put("entity", new ProductActiveComponent()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("readOnly", true);//生成列是否可编辑
//            params.put("readOnly", enableEdit == 1 ? false : true);//生成列是否可编辑
//            params.put("toolBarWidth", enableEdit == 1 ? 100 : 0);//操作区
            params.put("toolBarWidth", 0);//操作区
//            params.put("checkBox", "yes");
            params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
            mv.addObject("gridColumnsZJ",gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));


            params.put("moduleTable", moduleTable);
            mv.addObject("pageType","edit"); //页面类型：新增（add）、修改（edit）
            mv.addObject("enableEdit",enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            mv.addObject("ProductCarefullyChosen",chosen); //Listing库
            mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //Listing库各字段及属性
            mv.addObject("fieldsList", fieldsList);				//显示的字段
            mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
            mv.addObject("ajaxResult", ajaxResult);
            mv.addObject("ali1688AppKey", ApiConfig.getAli1688AppKey());
            mv.addObject("ali1688EcpApiUrl", ApiConfig.getAli1688EcpApiUrl());
            mv.addObject("extraButton", extraButton);
            mv.addObject("moduleTable", moduleTable);
            mv.setViewName(prefix + "/productcarefullychosen_edit");
        }
        return mv;

    }

    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: hlf
     * @date: 2022-05-09 11:41
     */
    @RequiresPermissions("business:productcarefullychosen:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        List<ProductCarefullyChosen> list = new ArrayList<ProductCarefullyChosen>();
        try {
            list = chosenService.queryDataList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }



    /**
     * @Description: 保存数据
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 11:41
     */
    @RequiresPermissions(value = {"business:productcarefullychosen:add", "business:productcarefullychosen:edit", "business:productcarefullychosen:delete"}, logical = Logical.OR)
    @Log(title = "精品库修改", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = chosenService.saveData(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * 导出Listing库
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @Log(title = "精品库导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("business:productcarefullychosen:export")
    @GetMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception{
        params.put("moduleTable", moduleTable);
        params.put("entity", new ProductCarefullyChosen());
        List<ProductCarefullyChosen> list = chosenService.queryDataList(params);
//        ExcelUtil<ProductInfo> util = new ExcelUtil<ProductInfo>(ProductInfo.class);
        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<ProductCarefullyChosen> util = new ExportExcelUtils<ProductCarefullyChosen>(moduleTable,new ProductCarefullyChosen());
        return util.exportExcel(list, fieldList, "精品库", "export");
    }

    /**
     * 导出Listing库
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @Log(title = "Listing导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("business:productcarefullychosen:export")
    @GetMapping("/export2")
    @ResponseBody
    public AjaxResult export2(@RequestParam Map<String, Object> params) throws Exception{
        params.put("moduleTable", moduleTable);
        params.put("entity", new ProductCarefullyChosen());
        List<ProductCarefullyChosen> list = chosenService.queryDataList(params);
//        ExcelUtil<ProductInfo> util = new ExcelUtil<ProductInfo>(ProductInfo.class);
        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<ProductCarefullyChosen> util = new ExportExcelUtils<ProductCarefullyChosen>(moduleTable,new ProductCarefullyChosen());
        return util.exportExcel(list, fieldList, "Listing库数据", "export");
    }
    
    /**
     * 导出Excel导入模板
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @RequiresPermissions("business:productcarefullychosen:import")
    @Log(title = "精品导入模板", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplateActive(@RequestParam Map<String, Object> params) throws Exception{
		params.put("moduleTable", moduleTable);
    	params.put("entity", new ProductActive()); 
    	params.put("getFieldAttributesType", "template");

    	List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<ProductBasis> util = new ExportExcelUtils<ProductBasis>(moduleTable,new ProductBasis());
        return util.exportExcel(null, fieldList, "精品导入模板", "template");
    }
    
    /**
     * 导入商品信息至商品库过渡表——数据提交
	 * @param productBasisItems 必要参数：基础商品库对应实体类（ProductBasis）的json格式字符串
     * @return
     * @author DH-Xxj
     */
    @Log(title = "精品批量修改基础数据", businessType = BusinessType.INSERT)
    @RequiresPermissions("business:productcarefullychosen:import")
    @PostMapping("/importpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult importSave(@RequestParam Map<String, Object> params){
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= chosenService.importBatch(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}